<?php

namespace app\api\controller;

use app\common\model\base\AttachmentModel;
use Qiniu\Auth;

class AttachmentController extends Base
{


    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->checkLogin();
        $this->model = new AttachmentModel();

    }

    public function index(){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d'); //当前页
        $sortName      = $this->request->param('sortName'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $searchData    = $this->getSearchData();
        $query = [];
        $fileType = $this->request->param('file_type','image');
        if($fileType!='all'){
            $query[]= ['file_type','=',$fileType];
        }
        $data          = ['total' => 0, 'rows' => []];
        $data['total'] = $this->model->withSearch('filter', $searchData)->where($query)->count();
        if ($data['total'] > 0) {
            $rows = $this->model->withSearch('filter', $searchData)
                ->where($query)
                ->page($pageNumber, $pageSize)
                ->order($order)
                ->order('id','desc')
                ->select()
                ->toArray();
            $rows = $this->model->_formatList($rows);
            $data['rows'] = $rows;
        }
        $this->result($data);
    }

    /**
     * 保存记录
     */
    public function saveLog(){
        $data = $this->request->param();
        $data['uid'] = $this->loginInfo['id'];
        $data['driver'] = 'qiniu';
        $data['module'] = 'mini';
        $data['original_name'] = $data['original_name'] ?? '';
        $data['file_type'] = $data['file_type'] ?? '';
        $data['file_size'] = $data['file_size'] ?? '';
        $data['upload_time'] = date('Y-m-d H:i:s');
        $data['spase_name'] = $data['spase_name'] ?? '';
        $info = $this->model->add($data);
        $this->result($info);
    }
    /**
     * 获取上传token
     */
    public function getToken(){
        $config   = config("filesystem.disks.qiniu");
        $auth = new Auth($config['accessKey'],$config['secretKey']);
        $expires = 3600;
        //自定义返回值
        $returnBody = '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"name":"$(x:name)"}';
        $policy = array(
            'returnBody' => $returnBody
        );
        $upToken = $auth->uploadToken($config['bucket'], null, $expires, $policy, true);
        $this->result($upToken);
    }











}
